package com.carleasoft.mps.file.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.carleasoft.mps.core.result.R;
import com.carleasoft.mps.file.bean.entity.FileManage;
import com.carleasoft.mps.file.bean.vo.JsonVo;
import com.carleasoft.mps.file.mapper.FileManageMapper;
import com.carleasoft.mps.file.service.FileManageService;
import com.carleasoft.mps.utils.MinioUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.time.LocalDateTime;
import java.util.*;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zang
 * @since 2022-07-25
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private FileManageService fileService;
    @Autowired
    private MinioUtils minioUtils;
    @Autowired
    private FileManageMapper fileManageMapper;

    @PostMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file) {
        List<String> upload = minioUtils.upload(new MultipartFile[]{file});
        String previewFileUrl = minioUtils.getPreviewFileUrl(upload.get(0));
        Map<String, String> res = new HashMap<>();
        res.put("fileName", upload.get(0));
        res.put("filePath", previewFileUrl);
        return R.ok(res);
    }

    @PostMapping("/getFileList")
    public R getFileList(@RequestBody List<String>ids){
        List<FileManage> fileManages = new ArrayList<>();
        if(ids.size() > 0) {
            fileManages = fileService.fileList(ids);
//            fileManages= fileService.list(Wrappers.<FileManage>lambdaQuery()
//            .in(FileManage::getId,ids));
//            for (FileManage fileManage : fileManages) {
//                String previewFileUrl = minioUtils.getPreviewFileUrl(fileManage.getMinioFileName());
//                fileManage.setFilePath(previewFileUrl);
//            }
        }
        return R.ok(fileManages);
    }

    @GetMapping(value = "/downLoad/{fileName}")
    public Object downLoad(@PathVariable(value = "fileName") String fileName) {

        ResponseEntity<byte[]> download = minioUtils.download(fileName);
        return download;
    }

    @PostMapping("/deleteFile/{fileName}")
    public R deleteFile(@PathVariable String fileName) {
        minioUtils.removeObjects(fileName);
        return R.ok();
    }

    @GetMapping(value = "/makeDir/{dirName}")
    public R makeDir(@PathVariable(value = "dirName") String dirName) {
        minioUtils.makeDir(dirName);
        return R.ok();
    }

    @GetMapping(value = "/getFilePath/{name}")
    public R getFilePath(@PathVariable(value = "name") String name) {
        String previewFileUrl = minioUtils.getPreviewFileUrl(name);
        return R.ok(previewFileUrl);
    }

    /**
     * 通过id或者相对路径访问图片
     *
     * @param request
     * @return
     */
    @GetMapping(value = "/view/byIdOrPath/**")
    public void viewByIdOrPath(HttpServletRequest request) throws IOException {
        String filePath = request.getRequestURI();
        String fileSuffix = null;
        String fileId = null;
        if (filePath.contains(StrUtil.DOT)) {
            fileSuffix = filePath.substring(filePath.indexOf(StrUtil.DOT), filePath.length());
            filePath = filePath.substring(filePath.indexOf("byIdOrPath") + "byIdOrPath".length(), filePath.length());
            fileService.viewPicByPath(filePath, fileSuffix);
        } else {
            fileId = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length());
            fileService.viewPicById(fileId);
        }
    }

    /**
     * 通过Id访问图片
     *
     * @param fileId
     * @return
     */
    @GetMapping(value = "/view/byId/{fileId}")
    public void viewById(@PathVariable(value = "fileId") String fileId) throws IOException {
        fileService.viewPicById(fileId);
    }

    /**
     * @param
     * @return
     */
    @GetMapping(value = "/view/byPath/{name}")
    public Object viewByPath(@PathVariable(value = "name") String name) throws IOException {
//        String filePath = request.getRequestURI();
        String substring = this.substring(name);
        ResponseEntity<byte[]> download = minioUtils.download(substring);
        return download;
    }


    public String substring(String name) {
        String str1 = name.substring(0, name.indexOf("?"));
        int i = StringUtils.ordinalIndexOf(str1, "/", 4);
        return str1.substring(i + 1, str1.length());

    }

    /**
     * 文件分片上传
     *
     * @param file
     */
    @PostMapping("/partFileUploadMinio")
    public R partFileUploadMinio(@RequestParam("file") MultipartFile file, @RequestParam("partFileIndex") String partFileIndexVo) {
//        log.info("minio文件分片上传操作,文件大小为:{}", partFileIndexVo);
        R result = fileService.filePartUploadMinio(file, partFileIndexVo);
        return result;

    }


    /**
     * 定时更新url
     */
//    @Scheduled(cron = "0 0 4 1/3 * ?")
//    @PostConstruct
    public void editMinioUrl() throws UnsupportedEncodingException {
        Map<String, String> hashMap = new HashMap<>();
        hashMap.put("C_CMS_ARTICLE", "{\"id\":\"ID\",\"fields\":[\"IMAGE_PATH\"]}");
        hashMap.put("C_DEAL_PROCESS", "{\"id\":\"ID\",\"fields\":[\"PROCESS_IMAGE\"]}");
        hashMap.put("C_INFORMATION_LIBRARY", "{\"id\":\"ID\",\"fields\":[\"IMAGE\"]}");
        hashMap.put("C_LIBRARY", "{\"id\":\"ID\",\"fields\":[\"IMAGE\"]}");
        hashMap.put("C_REASOURCE", "{\"id\":\"ID\",\"fields\":[\"IMAGE\"]}");
        hashMap.put("C_REPAIRS_MAINTAIN_MESSAGE", "{\"id\":\"ID\",\"fields\":[\"FILE\"]}");
        hashMap.put("C_TRAIN_CAR", "{\"id\":\"ID\",\"fields\":[\"FILE\"]}");
        hashMap.put("C_TRAIN_CONSUME", "{\"id\":\"ID\",\"fields\":[\"FILE\"]}");
        hashMap.put("C_TRAIN_DUTY", "{\"id\":\"ID\",\"fields\":[\"FILE\"]}");
        hashMap.put("C_TRAIN_EXAM", "{\"id\":\"ID\",\"fields\":[\"FILE\"]}");
        hashMap.put("C_TRAIN_PLAN", "{\"id\":\"ID\",\"fields\":[\"FILE\"]}");
        hashMap.put("E_TOPIC", "{\"id\":\"ID\",\"fields\":[\"TOPIC_IMAGE\"]}");
        hashMap.put("M_AUTHORITY_USER_BASICINFO", "{\"id\":\"ID\",\"fields\":[\"HEAD_PICTURE\"]}");
        hashMap.put("Q_NAIRE", "{\"id\":\"ID\",\"fields\":[\"NAIRE_IMAGE\"]}");

        for (Map.Entry<String, String> stringStringEntry : hashMap.entrySet()) {
            String tableName = stringStringEntry.getKey();
            String field = stringStringEntry.getValue();
            JSONObject fieldObj = JSONObject.parseObject(field);
            String id = fieldObj.getString("id");
            JSONArray fields = fieldObj.getJSONArray("fields");
            //查询数据
            List<JSONObject> json = fileManageMapper.listAll(tableName, id, fields);
            for (JSONObject obj : json) {
                if (obj.size() == 2) {
                    List<Map<String, String>> fieldList = new ArrayList<>();
                    for (Object f : fields) {
                        Map<String, String> map = new HashMap<>();
                        String fieldStr = (String) f;
                        // 解码URL中的特殊字符
                        Object ooj = obj.get(fieldStr);
                        String aaaaa = JSONObject.toJSONString(ooj);
                        Object parse = JSONArray.parse(aaaaa);
                        List<JsonVo> jsonVos = JSONArray.parseArray(parse.toString(), JsonVo.class);
                        if (CollUtil.isNotEmpty(jsonVos)) {
                            if (Objects.nonNull(jsonVos.get(0))) {
                                JsonVo jsonVo = jsonVos.get(0);
                                if (StrUtil.isNotBlank(jsonVo.getName())) {
                                    String previewFileUrl = minioUtils.getPreviewFileUrl(jsonVo.getName());
                                    jsonVo.setUrl(previewFileUrl);
                                    String s = JSON.toJSONString(jsonVo);
                                    map.put("k", fieldStr);
                                    map.put("v", "[" + s + "]");
                                    fieldList.add(map);
                                }
                            }
                        }
                    }
                    if (CollUtil.isNotEmpty(fieldList)) {
                        fileService.saveMinioUrl(fieldList, tableName, id, obj.getString(id));
                    }
                }

            }
        }

    }


}

